<template>
  <div>
    {{ viewdata.title }}
  </div>
  <div>
    <!-- {{ viewdata.list }} -->
    <ElSelect v-model="viewdata.pid" @change="changeProvince">
      <ElOption :value="-1" label="请选择省份"></ElOption>
      <ElOption v-for="d in viewdata.list" :value="d.pid" :label="d.province"> </ElOption>
    </ElSelect>

    <el-select v-model="viewdata.cid">
      <el-option :value="-1" label="请选择城市"></el-option>
      <el-option v-for="d in viewdata.clist" :value="d.cid" :label="d.city"></el-option>
    </el-select>

    {{ viewdata.pid }} - {{ viewdata.cid }}
  </div>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { Province, City } from '../../ts/Link'
import ApiService from '../../ts/ApiService'
import { BaseListResult } from '../../ts/BaseResult'
import { ElSelect, ElOption, ElMessageBox } from 'element-plus'
// 完成部门员工联动和班级学生联动功能
const viewdata = reactive({
  title: '省份城市联动',
  list: new Array<Province>(),
  clist: new Array<City>(),
  pid: -1,
  cid: -1,
})

function query() {
  // ts和以往js最大的区别点就是ts带有强类型系统
  // 好处是强类型的对象会有提示，必须写错字段或者方法
  // 坏处是所有的类型都要class定义出来
  ApiService.post('/linkinfo/queryAllProvince', {}, (data: BaseListResult<Province>) => {
    if (data.success) {
      viewdata.list = data.list
      return
    }
    ElMessageBox.alert(data.message)
  })
}

function changeProvince() {
  viewdata.cid = -1
  if (viewdata.pid == -1) {
    // 请选择省份的选项就是没有城市信息
    viewdata.clist = new Array<City>()
    return
  }
  // 查询省份对应的城市信息
  ApiService.post(
    '/linkinfo/queryCityByProvince',
    {
      pid: viewdata.pid,
    },
    (data: BaseListResult<City>) => {
      if (data.success) {
        viewdata.clist = data.list
        return
      }
      ElMessageBox.alert(data.message)
    },
  )
}

query()
</script>
<style></style>
